class Admin::MembersController < ApplicationController
  # GET /admin_members
  # GET /admin_members.xml
  def index
    @members = Member.paginate :page => params[:page], :per_page => 15, :joins => :person, :order => 'people.last_name, people.first_name'

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @members }
    end
  end

  # GET /admin_members/1
  # GET /admin_members/1.xml
  def show
    @member = Member.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @member }
    end
  end

  # GET /admin_members/new
  # GET /admin_members/new.xml
  def new
    @member = Member.new
    @member.person = Person.new
    @city = City.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @member }
    end
  end

  # GET /admin_members/1/edit
  def edit
    @member = Member.find(params[:id])
  end

  # POST /admin_members
  # POST /admin_members.xml
  def create
    @member = Member.new(params[:member])
    @member.person = Person.new(params[:person])
    @member.person.city = City.find_or_create_by_name(params[:city][:name])

    respond_to do |format|
      if @member.save
        flash[:notice] = 'Członek został zwalony.'
        format.html { redirect_to([:admin,@member]) }
        format.xml  { render :xml => @member, :status => :created, :location => @member }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @member.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /admin_members/1
  # PUT /admin_members/1.xml
  def update
    @member = Member.find(params[:id])
    @city = City.find_or_create_by_name(params[:city][:name])
    @member.person.city = @city

    respond_to do |format|
      if @member.update_attributes(params[:member]) and @member.person.update_attributes(params[:person])
        flash[:notice] = 'Zapisano zmiany.'
        format.html { redirect_to([:admin,@member]) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @member.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /admin_members/1
  # DELETE /admin_members/1.xml
  def destroy
    @member = Member.find(params[:id])
    @member.destroy

    respond_to do |format|
      format.html { redirect_to(admin_members_url) }
      format.xml  { head :ok }
    end
  end
end
